<script setup lang="ts" name="MultipleEditUserForm">
	import { reactive, ref, getCurrentInstance } from 'vue'
	import { ElMessage, FormInstance, FormRules } from 'element-plus'
	import { getGroupTreeApi, allChangeGroupApi, getStoreAllApi, allChangeStoreApi } from '@/addon/htscrm/api'
	import { cloneDeep } from 'lodash-es'
	import { t } from '@/lang'

	const instance = getCurrentInstance() as any
	const { $convert } = instance.appContext.config.globalProperties

	const defaultFormData : editGroupItem = {
		id: [],
		title: [],
		store_id: 0
	}
	/** 表单实例 */
	const formRef = ref<FormInstance>()
	/** 表单数据 */
	const formData = ref<editGroupItem>({ ...defaultFormData })

	// 表单规则
	const formRules = reactive<FormRules>({
		name: [{ required: true, message: t('group.form.name.placeholder'), trigger: 'blur' }]
	})

	const storeList = ref<Partial<IStoreItem>[]>([]);

	/**
	 * @description 初始化
	 */
	function init(row ?: IGroupItem, isEdit = false) {

		formRef.value?.resetFields()
		formData.value = { ...row }
		getStoreList()
	}

	/**
	 * @description 获取上级门店
	 */
	async function getStoreList() {
		const res = await getStoreAllApi();
		storeList.value = [{ id: 0, title: t("default.store.name") }, ...res.data];
	}

	/**
	 * @description 提交保存
	 */
	function submit() {
		return new Promise(async (resolve, reject) => {
			const params = cloneDeep({
				...formData.value,
				id: formData.value.id.join(','),
			})
			await allChangeStoreApi(params)
			ElMessage.success(t('save.success'))
			resolve(true)
		})
	}

	defineExpose({
		init,
		submit
	})
</script>

<template>
	<el-form class="f-form" ref="formRef" label-width="100px" :model="formData" :rules="formRules">
		<el-form-item :label="t('CurrentlySelected')">
			<el-tag class="mr-2 mb-2" v-for="(item,index) in formData.title" :key="index"
				type="primary">{{item && item.length > 10 ? item.substring(0, 10) + '...' : (item || '--')}}</el-tag>
		</el-form-item>
		<el-form-item label="所属门店">
			<el-select v-model="formData.store_id" filterable :placeholder="t('form.store_id.placeholder')"
				style="width: 240px">
				<el-option v-for="item in storeList" :key="item.id" :label="item.title" :value="item.id" />
			</el-select>
		</el-form-item>
	</el-form>
</template>